<?php

namespace App\Services\ApplyGoldCoinWithdraw;

use App\Models\User;
use App\Models\Withdraw;
use Illuminate\Support\Facades\Log;

class ApproveGoldCoinWithdraw
{
	/**
	 * @var User
	 */
	protected $user;
	
	/**
	 * @var Withdraw
	 */
	protected $withdraw;
	
	public function __construct(Withdraw $withdraw)
	{
		$this->withdraw = $withdraw;
		$this->user = $withdraw->user;
	}
	
	protected function isWithdrawOn()
	{
		return Withdraw::isWithdrawOn();
	}
	
	protected function isAlipayMoneyEnough()
	{
		$activeFund = cashier('alibatch')->findActive();
		return big_decimal($activeFund)->isGreaterThan($this->withdraw->actual_amount);
	}
	
	protected function validate()
	{
		if (! $this->isWithdrawOn()) {
			Log::error('平台尚未开放提现功能');
			return false;
		} elseif (! $this->user->isAlipayBound()) {
			Log::error('提现账号未绑定');
			return false;
		} elseif (! $this->isAlipayMoneyEnough()) {
			Log::error('提现资金正在入账请稍后再试');
			return false;
		}
		return true;
	}
	
	public function approve($isBatch = false)
	{
		if (! $this->validate()) return;
		
		if ($isBatch) {
			$withdraws = collect();
			$withdraws->push($this->withdraw);
			cashier('alibatch')->transferWithdraw($withdraws);
		} else {
			cashier('alipay')->transferWithdraw($this->withdraw);
		}
	}
}
